package com.niuwa.p2p.service.user.impl;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.dao.user.UserDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.user.User;
import com.niuwa.p2p.exception.BusinessException;
import com.niuwa.p2p.service.user.UserService;

/**
 * 
 * @ClassName: UserService
 * @Descriptio:用户接口实现   
 * @author:    jishengjun
 */
@Service
public class UserServiceImpl implements UserService {
	
	/** 用户DAO spring扫包自动注入*/
	@Autowired
	private UserDao userDao;
	
	private static Logger logger = Logger.getLogger(UserService.class);
	
	/**
	 * 选取全部用户
	 * 
	 * @return List<User> 用户集合
	 * @throws Exception
	 */
	@Override
	public List<User> listUserAll()  throws Exception {
		return userDao.selectUserAll();
	}
	
	/**
	 * 新增用户
	 * 
	 * @param user 添加的用户对象
	 * @throws Exception
	 */
	@Override
	public void saveUser(User user) throws Exception {
		// 新增用户	
		if ((isNotempty(user.getLoginName()) && isUserExist(user.getLoginName()))
				|| (null !=userDao.selectByUserId(user.getId()))) {
			throw new BusinessException("userService.userIsAlreadyExist");
		} else {
			userDao.insertUser(user); 			
		}
	}
	
	/**
	 * 更新用户
	 * 
	 * @param user 更新的用户对象
	 * @throws Exception
	 */
	@Override
	public int updateUser(User user,String loginName) throws Exception {
		// 更新用户
		if ((isUserExist(user.getLoginName()))
				||	(null !=userDao.selectByUserId(user.getId()))) {
			user.setUpdater(loginName);
			Date  updateTime=new Date();
			Timestamp updateTime2=new Timestamp(updateTime.getTime());
			user.setUpdateTime(updateTime2);
			return userDao.updateByUserSelective(user);			
		} else {
			throw new BusinessException("userService.userIsNotExist");
		}
	}
	
	/**
	 * 删除用户
	 * 
	 * @param user 删除的用户对象
	 * @throws Exception
	 */
	@Override
	public int deleteUser(User user) throws Exception {
		userDao.deleteUserRole(user.getId());
		return userDao.deleteByUserID(user.getId());
	}

	/**
	 * 取得用户
	 * 
	 * @param userId 用户Id
	 * @return User 选取的用户
	 * @throws Exception
	 */
	@Override
	public User getUser(long userId)  throws Exception {
		return userDao.selectByUserId(userId);
	}

	/**
	 * 取得用户
	 * 
	 * @param loginName 登陆名
	 * @return User 选取的用户
	 * @throws Exception
	 */
	@Override
	public User getUser(String loginName)  throws Exception {
		return userDao.selectByLoginName(loginName);
	}

	/**
	 * 
	 * 分页查询
	 * paramMap 查询参数
	 */
	
	public PageBean<User> search(Map<String, Object> paramMap){
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		
		int totalCount = userDao.getUserCountByCondition(paramMap);
		PageBean<User> page = new PageBean<User>(totalCount);
		// 当前页
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(userDao.getUserByCondition(paramMap));
		return page;
	}

	
	/**
	 * 验证用户登陆名唯一性
	 * 
	 * @param  loginName 登陆名
	 * @return true:已存在  false:不存在
	 * @throws Exception
	 */
	@Override
	public boolean isUserExist(String loginName) throws Exception{
		if(null != userDao.selectByLoginName(loginName)){			
			return true;
		}		
		return false;
	}
	
	/**
	 * 
	 *格式化时间
	 * @param paramMap
	 * @return Map
	 *
	 */
		public Map<String, Object> formatDate(Map<String, Object> paramMap) {
			String dateFromat1 = "MM/dd/yyyy";
			String dateFromat2 = "yyyy-MM-dd HH:mm:ss";
			SimpleDateFormat sdf1 = new SimpleDateFormat(dateFromat1);
			SimpleDateFormat sdf2 = new SimpleDateFormat(dateFromat2);
			String beginTime = (String) paramMap.get("beginTime");
			String endTime = (String) paramMap.get("endTime");
			if ((beginTime != null )&&!("".equalsIgnoreCase(beginTime))) {
				try {
					Date beginTime2 = sdf1.parse(beginTime);
					String beginTime3 = sdf2.format(beginTime2);
					paramMap.put("beginTime", beginTime3);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if ((endTime != null)&&!("".equalsIgnoreCase(endTime)))
				try {
					Date endTime2 = sdf1.parse(endTime);
					String endTime3 = sdf2.format(endTime2);
					paramMap.put("endTime", endTime3);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return paramMap;
		}
	
	/**
	 * 编辑用户Grid表单
	 * 
	 * @param  user 用户对象
	 * @param  oper Gird操作符     
	 *         add：   添加
     *         edit：编辑
     *         del：   删除
	 * @throws Exception
	 */
	@Override
	public void editUser(User user, String oper) throws Exception{
//		// 根据用户操作符，执行操作
//		if (oper.equalsIgnoreCase("add")) {
//			// 添加用户
//		    logger.debug("UserAction.userEditGridEntry saveUser Start");
//		    // 取得用户信息
//		    User newUser =  user;		
//		    // 保存
//			saveUser(newUser);
//			logger.debug("UserAction.userEditGridEntry saveUser End");
//
//	   } else if (oper.equalsIgnoreCase("edit")) {		
//			// 更新用户
//		    logger.debug("UserAction.userEditGridEntry updateUser Start");
//		    // 取得用户信息
//		    User updateUser =  user;
//		    // 更新
//		    updateUser(updateUser);
//			logger.debug("UserAction.userEditGridEntry updateUser End");
//     			
//	   } else if (oper.equalsIgnoreCase("del")) {
//		     // 删除用户
//		    String deletUserId =  user.getId();
//		    logger.debug("UserAction.userEditGridEntry deleteUser Start");
//		    // 取得删除用户id符（多用户以逗号分隔）
//		    // 例： 单用户：1  多用户：1，2，3		    
//		    StringTokenizer ids = new StringTokenizer(deletUserId, ",");
//		    // 循环删除用户
//		    while (ids.hasMoreTokens()) {
//		        // 设置需要删除的用户
//		    	String removeId = ids.nextToken();	
//		    	User deleteUser = new User();
//		    	deleteUser.setId(removeId);
//		        // 删除
//		    	deleteUser(deleteUser);	
//		        logger.debug("Deleted User: " + removeId);
//		    }
//		    logger.debug("UserAction.userEditGridEntry deleteUser End");
//	   }
	}
	
	/**
	 * TODO 转入共通
	 * 判断字符串是否为空 
	 *  
	 */
	private boolean isEmpty(String s){
		return null == s || "".equals(s.trim()) || "_empty".equals(s);
	}
	
	/**
	 * TODO 转入共通
	 * 判断字符串是否不为空 
	 *  
	 */
	private boolean isNotempty(String s){
		return !isEmpty(s);
	}
			
	/**
	 * 根据用户名和密码获得用户
	 * @param loginName
	 * @param password
	 * @return
	 */
	public User getUser(String loginName,String password){
		HashMap<String,String> paramMap=new HashMap<String,String>();
		paramMap.put("loginName",loginName );
		paramMap.put("password", password);
	    return	userDao.getUser(paramMap);
		
	}

	@Override
	public List<HashMap<String, String>> getUserResources(String loginName,
			String password) {
		HashMap<String,String> paramMap=new HashMap<String,String>();
		paramMap.put("loginName",loginName);
		paramMap.put("password", password);
	    return	userDao.getUserResources(paramMap);
	}



	@Override
	public User login(String loginName, String password) throws Exception {
		return userDao.login(loginName, password);
	}
	
	
	/**
	 * 
	 *根据登入名查询密码
	 * @param loginName
	 * @return password
	 *
	 */
	@Override
	public String getPasswordByLoginName(String loginName){
		
		return userDao.getPasswordByLoginName(loginName);
		
	}

	
	/**
	 * 判断登入名称是否已经存在
	 * @param user
	 * @return
	 */
	@Override
	public List<User> searchUserByloginName(User user) {
	
			return userDao.searchUserByloginName(user.getLoginName());

	
	}

	@Override
	public void addUser(User user, String currentLoginName) {
	Map<String,Object>  userParamMap=new HashMap<String, Object>();
	userParamMap.put("userName",user.getUserName());
	userParamMap.put("loginName", user.getLoginName());
	userParamMap.put("loginPassword", user.getLoginPassword());
	userParamMap.put("tel", user.getTel());
	userParamMap.put("email", user.getEmail());
	userParamMap.put("status", user.getStatus());
	userParamMap.put("delFalg", 'N');
	userParamMap.put("creater",currentLoginName );
	userParamMap.put("updater", currentLoginName);
	Date createTime=new Date();
	userParamMap.put("createTime", createTime);
	userParamMap.put("updateTime", createTime);
	userDao.addUser(userParamMap);
	};

}
